﻿using gl_SMT.Model;
using Microsoft.Office.Interop.Excel;
using Microsoft.Win32;
using SMTUploadProductionData.model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Application = Microsoft.Office.Interop.Excel.Application;

namespace gl_SMT.View
{
    /// <summary>
    /// ymh_ControlDataSelect.xaml 的交互逻辑
    /// </summary>
    public partial class ymh_DataSelect : UserControl
    {
        public ymh_DataSelect()
        {
            InitializeComponent();
            this.Loaded += Ymh_DataSelect_Loaded;
        }

        public string MachineName { get; set; }
        DatabaseReadWrite database = new DatabaseReadWrite();
        private void Ymh_DataSelect_Loaded(object sender, RoutedEventArgs e)
        {
            dp_SatrtDate.Text = DateTime.Now.ToString();//开始日期
            dp_EndDate.Text = DateTime.Now.ToString();//结束日期
            InitializeTime();//初始化时间
            SelectData();//查询数据
        }

        private void InitializeTime()
        {
            for (int i = 0; i < 24; i++)//小时
            {
                cb_sHour.Items.Add(i.ToString("D2"));
                cb_eHour.Items.Add(i.ToString("D2"));
            }
            cb_sHour.SelectedIndex = 0;
            cb_eHour.SelectedIndex = 23;

            for (int i = 0; i < 60; i++)//分钟
            {
                cb_sMinute.Items.Add(i.ToString("D2"));
                cb_sSecond.Items.Add(i.ToString("D2"));
                cb_eMinute.Items.Add(i.ToString("D2"));
                cb_eSecond.Items.Add(i.ToString("D2"));
            }
            cb_sMinute.SelectedIndex = 0;
            cb_sSecond.SelectedIndex = 0;
            cb_eMinute.SelectedIndex = 59;
            cb_eSecond.SelectedIndex = 59;
        }

        private void btn_Select_Click(object sender, RoutedEventArgs e)
        {
            SelectData();
        }

        private void SelectData()
        {
            List<ymh_model> ymh_Model = SelectContent();
            dataGrid.ItemsSource = ymh_Model;//数据绑定
            txt_SelectNumber.Text = ymh_Model.Count.ToString();//获取查询数据的行数
            Task.Run(() => Dispatcher.Invoke(() => { txt_PcbNumber.Text = ymh_Total().ToString(); }));//获取生产数量 
            txt_CycleTime.Text = ProductionCycle(MachineName.Split(' ')[1]).ToString();
        }

        private void btn_Export_Click(object sender, RoutedEventArgs e)
        {
            List<ymh_model> ymh_Model = SelectContent();
            SaveFileDialog saveFile = new SaveFileDialog();//初始化一个SaveFileDialog
            saveFile.Filter = "Excel Worksheets|*.xls";//保存的文件格式
            if (saveFile.ShowDialog() == true)
            {
                Application excelApp = new Application();
                Workbook workbook = excelApp.Workbooks.Add();
                Worksheet worksheet = (Worksheet)workbook.ActiveSheet;
                for (int i = 0; i < dataGrid.Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1] = dataGrid.Columns[i].Header.ToString();// 设置表头
                }
                for (int i = 0; i < ymh_Model.Count; i++)//添加行的内容
                {
                    worksheet.Cells[2 + i, 1] = ymh_Model[i].MachineName;
                    worksheet.Cells[2 + i, 2] = ymh_Model[i].RunningStatus;
                    worksheet.Cells[2 + i, 3] = ymh_Model[i].ProductName;
                    worksheet.Cells[2 + i, 4] = ymh_Model[i].Cycle;
                    worksheet.Cells[2 + i, 5] = ymh_Model[i].TotalQuantity;
                    worksheet.Cells[2 + i, 6] = ymh_Model[i].NumberBoards;
                    worksheet.Cells[2 + i, 7] = ymh_Model[i].TotalNumber;
                    worksheet.Cells[2 + i, 8] = ymh_Model[i].Time;
                }
                // 自动调整列宽
                worksheet.Columns.AutoFit();

                // 保存文件
                workbook.SaveAs(saveFile.FileName);
                workbook.Close();
                excelApp.Quit();

                // 释放 COM 对象
                System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                MessageBox.Show("导出完成");
            }
        }

        /// <summary>
        /// 获取生产总数
        /// </summary>
        /// <returns></returns>
        private int ymh_Total()
        {
            int TotalQuantity = 0;
            List<ymh_model> list_ymh = SelectContent();
            for (int j = 1; j < list_ymh.Count; j++)
            {
                try
                {
                    if (list_ymh[j].TotalQuantity == "") continue;
                    int pcbNumber = int.Parse(list_ymh[j - 1].TotalQuantity);
                    if (list_ymh[j].TotalQuantity == "0") TotalQuantity += pcbNumber;//数据等于0的时候就是一个型号的产品开始生产，也有同一个产品生产多次的情况
                    if (j == list_ymh.Count - 1) TotalQuantity += pcbNumber;//再加上最后一行的数据
                }
                catch (Exception)
                {
                    continue;
                }
            }
            return TotalQuantity;
        }

        private int ProductionCycle(string Name)
        {
            string select = $"SELECT *FROM (SELECT *,ROW_NUMBER() OVER (PARTITION BY TotalQuantity ORDER BY Time DESC ) AS rn " +
                            $"FROM ymh_Producedate WHERE CAST(Time AS DATE) = CAST(GETDATE() AS DATE) and MachineName='{Name}' and Cycle!='0' ) t WHERE rn = 1 order by Time asc";
            System.Data.DataTable dt = database.SelectData(select);
            int Cycle = 0;
            List<DataRow> list_row = dt.Rows.Cast<DataRow>().ToList();
            Cycle = (int)(list_row.Average(t => (int)t.ItemArray[4]));
            return Cycle;
        }

        private  List<ymh_model> SelectContent()
        {
            string sta_DateTime = $"{dp_SatrtDate.Text} {cb_sHour.Text}:{cb_sMinute.Text}:{cb_sSecond.Text}";//获取开始日期和时间
            string end_DateTime = $"{dp_EndDate.Text} {cb_eHour.Text}:{cb_eMinute.Text}:{cb_eSecond.Text}";//获取结束日期和时间
            List<ymh_model> list_ymh =  database.QueryData<ymh_model>("ymh_Producedate", "MachineName", MachineName.Split(' ')[1], sta_DateTime, end_DateTime, "Time","date");
            return list_ymh;
        }
    } 
}
